import { ref } from "vue";
import { useI18n } from "vue-i18n";
interface DateInfo {
	year: number;
	month: number;
	day: number;
	formatted: string;
}
// 获取最近7天日期
export const useTimeGenerator = () => {
	const getCurrentDateInfo = (date: Date): DateInfo => {
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		const day = date.getDate();

		return {
			year,
			month,
			day,
			formatted: [
				year,
				month >= 10 ? month : `0${month}`,
				day >= 10 ? day : `0${day}`,
			].join("-"),
		};
	};

	const getTime = (days = 7): string[] => {
		const currentDate = new Date();
		const baseTimestamp = currentDate.getTime();
		const oneDay = 24 * 3600 * 1000;

		const dateArray: DateInfo[] = [];

		// 获取从今天往前推的日期
		for (let i = days - 1; i >= 0; i--) {
			const targetDate = new Date(baseTimestamp - i * oneDay);
			dateArray.push(getCurrentDateInfo(targetDate));
		}

		return dateArray.map((info) => info.formatted);
	};

	return {
		getTime,
	};
};

interface TimeParts {
	hours: string;
	minutes: string;
	seconds: string;
}

export const useTimeFormatter = () => {
	const { t } = useI18n();

	const formatTimeUnit = (value: number): string => {
		return value < 10 ? `0${value}` : `${value}`;
	};

	const getTimeParts = (seconds: number): TimeParts => {
		const hours = formatTimeUnit(Math.floor((seconds / 3600) % 24));
		const minutes = formatTimeUnit(Math.floor((seconds / 60) % 60));
		const secondsFormatted = formatTimeUnit(Math.floor(seconds % 60));

		return { hours, minutes, seconds: secondsFormatted };
	};

	const getSecond = (seconds: number): string => {
		const { hours, minutes, seconds: sec } = getTimeParts(seconds);
		let result = "";

		if (hours !== "00") {
			result += `${hours} ${t("statistics.hour")}`;
		}

		if (minutes !== "00") {
			result += `${minutes} ${t("recordDetails.minute")}`;
		}

		// 总是显示秒数
		result +=
			sec !== "00"
				? `${sec} ${t("recordDetails.sec")}`
				: `0 ${t("recordDetails.sec")}`;

		return result;
	};

	return {
		getSecond,
	};
};
